﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;

namespace MvcShop.Extensions
{
    /// <summary>
    /// 缩略图处理类
    /// </summary>
    public static class CreateThumbnail
    {
        /// <summary>
        /// 传入图片流生成指定宽和高的缩略图
        /// </summary>
        /// <param name="imageStream">要生成缩略图的图片流</param>
        /// <param name="desiredWidth">生成缩略图的宽度</param>
        /// <param name="desiredHeight">生成缩略图的高度</param>
        /// <returns>位图缩略图</returns>
        public static Bitmap CreateThumbnails(Bitmap originalBmp, int desiredWidth, int desiredHeight)
        {
            // If the image is smaller than a thumbnail just return it
            if (originalBmp.Width <= desiredWidth && originalBmp.Height <= desiredHeight)
            {
                return originalBmp;
            }

            int newWidth, newHeight;
            decimal desiredRatio = Math.Min((decimal)desiredWidth / originalBmp.Width, (decimal)desiredHeight / originalBmp.Height);
            newWidth = Convert.ToInt32(Math.Round(originalBmp.Width * desiredRatio));
            newHeight = Convert.ToInt32(Math.Round(originalBmp.Height * desiredRatio));

            // This code creates cleaner (though bigger) thumbnails and properly
            // and handles GIF files better by generating a white background for
            // transparent images (as opposed to black)
            // This is preferred to calling Bitmap.GetThumbnailImage()
            Bitmap bmpOut = new Bitmap(newWidth, newHeight);

            using (Graphics graphics = Graphics.FromImage(bmpOut))
            {
                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphics.FillRectangle(Brushes.White, 0, 0, newWidth, newHeight);
                graphics.DrawImage(originalBmp, 0, 0, newWidth, newHeight);
            }

            return bmpOut;
        }
    }
}
